from datetime import datetime

from elasticsearch_dsl import (
    Document,
    InnerDoc,
    Short,
    Keyword,
    Long,
    Float,
    Nested,
    Text,
    Float,
    Date,
    Join,
    Boolean,
    connections,
    analyzer, Object,
)


from config import settings
from core.es import Index_KJJ_DEPARTMENT

Index_DEPARTMENT = Index_KJJ_DEPARTMENT

connections.create_connection(hosts=[settings.dsl], timeout=120)

class Oindex(InnerDoc):
    oindex_bread = Long()
    oindex_high = Long()
    oindex_deep = Long()
    oindex_multi = Long()
    oindex_tight = Long()
    year = Long()


class Region(InnerDoc):
    """
    地区
    """

    province = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word")
    city = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word")
    district = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word")


class Department(Document):
    institution_name = Text(fields={"keyword": Keyword()})
    in_kexie = Boolean()
    level = Long()
    self_kexie = Boolean()
    establishment_time = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word",
                              position_increment_gap=100)
    participants = Long()
    institution_type = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word")  # 机构类型（高/国）
    institution_location = Text(fields={"keyword": Keyword(ignore_above=256)}, analyzer="ik_max_word")

    address = Object(Region)
    activities_of_participants = Long()
    update_at = Date(required=True)  # for es
    create_at = Date(required=True)  # for es
    m_activity_overview = Nested()
    m_contact_overview = Nested()
    m_activity_span = Nested()
    oindex = Nested(Oindex)  # 雷达图
    acc_activity = Long()
    acc_join = Long()
    acc_alumni = Long()

    class Index:
        name = Index_DEPARTMENT
        settings = {
            "number_of_shards": 1,
            "number_of_replicas": 0,
        }

    def save(self, **kwargs):
        # if there is no date, use now
        if self.create_at is None:
            self.create_at = datetime.now()
        return super().save(**kwargs)


def setup():
    """Create an IndexTemplate and save it into elasticsearch."""
    index_template = Department._index.as_template("base")
    index_template.save()


if __name__ == "__main__":
    # initiate the default connection to elasticsearch
    connections.create_connection(hosts=[settings.dsl], timeout=120)

    # create index
    setup()
    Department.init()
